<template>
  <div id="flow-control-filter">
    <div class="main-cont">
      <iToolbar v-on:click="handleToolClick" :buttonsObj="buttonsObj"></iToolbar>
      <el-container>
        <el-main>
          <el-table  :data="tableData">
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column label="控制层级">
              <template slot-scope="scope">
                {{ ctrlLevelDict[scope.row.linkType] }}
              </template>
            </el-table-column>
            <el-table-column prop="linkName" label="层级名称"></el-table-column>
            <el-table-column label="过滤器参数">
              <template slot-scope="scope">
                频率:{{ frequencyDict[scope.row.linkData.type]}}
                交易流量:{{ scope.row.linkData.value}}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" v-on:click="ctrlFiletrUpdate(scope.row)">修改</el-button>
                <el-button type="text" size="small" v-on:click="isDelete(scope.row.linkId, scope.row.filterId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
          </el-pagination>
        </el-main>
      </el-container>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @close="cancel('ruleForm')" width="900px">
      <el-form :model="formData" ref="ruleForm" :rules="rules" label-position="left">
        <el-row>
          <el-col :span='12'>
            <el-form-item label="过滤器名称" :label-width="formLabelWidth" prop="filterName">
              <el-input value="流量控制过滤器" autocomplete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span='12'>
            <el-form-item label="控制级别" :label-width="formLabelWidth" prop="linkType">
              <el-select popper-class="zIndex-popper" v-model="formData.linkType" placeholder="请选择" @change="changeVal(formData.linkType)" :disabled="isDisabled">
                <el-option
                  v-for="item in ctrlLevel"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label="级联数据" :label-width="formLabelWidth" prop="linkId">
              <el-select popper-class="zIndex-popper" v-model="formData.linkId" placeholder="请选择" :disabled="isDisabled">
                <el-option
                  v-for="item in levelDataOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
           <el-col :span='12'>
            <el-form-item label="控制流量(次)" :label-width="formLabelWidth" prop="_controlFlow">
              <el-input v-model="formData._controlFlow" autocomplete="off" placeholder="控制流量(次)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label="控制频率" :label-width="formLabelWidth" prop="_controlFrequency">
              <el-select popper-class="zIndex-popper" v-model="formData._controlFrequency" placeholder="请选择">
                <el-option label = '每秒钟' value = '00'></el-option>
                <el-option label = '每分钟' value = '01'></el-option>
                <el-option label = '每小时' value = '02'></el-option>
                <el-option label = '每天' value = '03'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset()">重置</el-button>
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click.native="ctrlFilterCreate('ruleForm', addOrUpsate)">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
  import { gateWay } from '../../gateWay/dict/rule-dict'
  import ajax from '../../../api/ajax/ajax'
  import api from '../../../api/url'
  import iToolbar from '../../iapadmin/comm/iToolbar/iToolbar'
  import { getDateTime } from '../../../assets/js/index'
  import {VHeader} from '../../../components/index'
  export default {
    name: 'concurrency-dontrol-filter',
    components: {
      iToolbar: iToolbar,
      VHeader
    },
    data () {
      return {
        addOrUpsate: '',
        dialogFormVisible: false,
        dialogTitle: '',
        // 控制是否禁用下拉选择框
        download: false,
        save: false,
        isDisabled: false,
        initFormData: {},
        editData: {},
        buttonsObj: [
          {
            text: '新增',
            oprType: 'addFilter'
          }
        ],
        tableData: [],
        formLabelWidth: '120px',
        // 控制级别下拉选项数据
        ctrlLevel: [
          {
            label: '关联网关',
            value: '00'
          },
          {
            label: '关联模块',
            value: '01'
          },
          {
            label: '关联接口',
            value: '02'
          }
        ],
        levelDataOption: [
        ],
        formData: {
          linkData: {},
          linkType: '',
          linkId: '',
          _controlFlow: '',
          _controlFrequency: '',
          _developer: '00'
        },
        // 校验规则
        rules: {
          linkType: [
            { required: true, message: '请选择控制级别', trigger: 'change' }
          ],
          linkId: [
            { required: true, message: '请选择级别关联数据', trigger: 'change' }
          ],
          _controlFrequency: [
            { required: true, message: '请选择控制频率', trigger: 'change' }
          ],
          _controlFlow: [
            { required: true, message: '请输入控制流量', trigger: 'blur' },
            { type: 'number', message: '只能输入数字' }
          ]
        },
        // 分页数据
        total: 0,
        currentPage: 1,
        pageSize: 10
      }
    },
    methods: {
      // 获取所有规则数据
      getAllData (pageNum = 1, pageSize = 10) {
        ajax.post(api.FLOWFILTERLIST + '?pageNum=' + pageNum + '&pageSize=' + pageSize, {}).then(res => {
          if (res.list.length > 0) {
            this.total = res.total
            this.pageSize = res.pageSize
            let ruleArr = res.list
            let changeArr = []
            ruleArr.forEach((item, key) => {
              item.createTime = getDateTime(new Date(item.createTime), 'ss')
              changeArr.push(item)
            })
            this.tableData = changeArr
            this.currentPage = pageNum
          } else {
            this.tableData = []
          }
        }).catch(() => {})
      },
      // 工具栏操作
      handleToolClick (opt) {
        switch (opt) {
          case 'addFilter':
            this.addFilter()
            break
          default:
            break
        }
      },
      // 提交保存发送请求
      savePost () {
        let linkData = {
          type: this.formData._controlFrequency,
          value: this.formData._controlFlow.toString()
        }
        this.formData.linkData = linkData
        ajax.post(api.ADDFLOWFILTER, this.formData, true).then(res => {
          if (res === 'success') {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.getAllData()
            this.dialogFormVisible = false
          }
        }).catch((err) => {
          if (err.errorMsg) {
            this.$message.error(err.errorMsg)
          }
        })
      },
      // 提交更新发送请求
      saveUpdatePost () {
        let linkData = {
          type: this.formData._controlFrequency,
          value: this.formData._controlFlow.toString()
        }
        this.formData.linkData = linkData
        this.isDisabled = false
        ajax.post(api.MODIFYFLOWFILTER, this.formData).then(res => {
          if (res === 'success') {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.getAllData(this.currentPage)
            this.dialogFormVisible = false
          }
          if (res.errorMsg) {
            this.$message.error(res.errorMsg)
          }
        }).catch(() => {})
      },
      // 更新或者修改并发控制器
      ctrlFilterCreate (formName, addOrUpsate) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (addOrUpsate === 'add') {
              this.savePost()
            } else if (addOrUpsate === 'update') {
              this.saveUpdatePost()
            }
          } else {
            return false
          }
        })
      },
      addFilter () {
        this.editData = JSON.parse(JSON.stringify(this.initFormData))
        this.dialogTitle = '新增'
        this.isDisabled = false
        this.addOrUpsate = 'add'
        this.dialogFormVisible = true
      },
      // 关闭弹窗
      cancel (formName) {
        this.formData = {...this.initFormData}
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
        this.dialogFormVisible = false
      },
      // 删除一个规则
      ruleDelete (linkId, filterId) {
        ajax.post(api.REMOVEFLOWFILTER, {
          linkId: linkId,
          filterId: filterId
        }).then(res => {
          if (res === 'success') {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.getAllData()
            this.dialogFormVisible = false
          }
        }).catch(() => {})
      },
      // 确认是否进行删除操作
      isDelete (linkId, filterId) {
        this.$confirm('确定要删除当前过滤器吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.ruleDelete(linkId, filterId)
        }).catch(err => {
          console.info(err)
        })
      },
      // 编辑当前流量控制过滤器
      ctrlFiletrUpdate (data) {
        this.addOrUpsate = 'update'
        this.dialogTitle = '修改流量控制过滤器'
        switch (data.linkType) {
          case '00':
            this.getListGateway()
            break
          case '01':
            this.getListApiModule()
            break
          case '02':
            this.getListApiInterface()
            break
        }
        data._controlFrequency = data.linkData.type
        data._controlFlow = Number(data.linkData.value)
        data._filterParam = 10
        data._developer = '00'
        this.formData = {...data}
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
        this.editData = JSON.parse(JSON.stringify(data))
        this.isDisabled = true
        this.dialogFormVisible = true
      },
      // 切换分页
      handleCurrentChange (val) {
        this.getAllData(val)
      },
      changeVal (val) {
        this.formData.linkId = ''
        switch (val) {
          case '00':
            this.getListGateway()
            break
          case '01':
            this.getListApiModule()
            break
          case '02':
            this.getListApiInterface()
            break
        }
      },
      // 获取网关环境列表
      getListGateway () {
        ajax.post(api.LISTGATEWAYENV, {
          'pageNum': '1',
          'pageSize': '20'
          }).then(res => {
            this.getLoopData(res.list, 'gwEnvName', 'gwEnvId')
        }).catch(() => {})
      },
      // 获取服务模块列表
      getListApiModule () {
        ajax.post(api.LISTAPIMODULE, {
          'pageNum': '1',
          'pageSize': '20'
          }).then(res => {
            this.getLoopData(res.list, 'moduleName', 'moduleId')
        }).catch(() => {})
      },
      // 获取关联接口列表
      getListApiInterface () {
        ajax.post(api.LISTAPIINTERFACE, {
          'pageNum': '1',
          'pageSize': '20'
          }).then(res => {
            this.getLoopData(res.list, 'interfaceName', 'interfaceId')
        }).catch(() => {})
      },
      // 循环拿到获取的关联值
      getLoopData (arr, name, typeId) {
        let handleArr = []
        arr.forEach((item, key) => {
          let obj = {}
          obj.label = item[name]
          obj.value = item[typeId]
          handleArr.push(obj)
        })
        this.levelDataOption = handleArr
      },
      // 重置表单
      reset () {
        this.formData = {...this.editData}
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    created () {
      this.getAllData()
      this.initFormData = JSON.parse(JSON.stringify(this.formData))
    },
    computed: {
      ctrlLevelDict () {
        return gateWay.ctrlLevel
      },
      frequencyDict () {
        return gateWay.frequency
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  #flow-control-filter
    height 100%
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 16px
      font-weight normal
    .main-cont
      width 100%
      height calc(100% - 62px)
      overflow: auto
      overflow-x hidden
      padding 10px 0 0 10px
    .el-dialog
      .el-col
        padding 0 12px
    .el-pagination
      padding-top 20px
    .el-select
    .el-input
      width 100%
</style>
